/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.coupon.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ykht.proj.admin.api.feign.RemoteUserService;
import com.ykht.proj.admin.api.vo.UserVO;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.log.annotation.SysLog;
import com.ykht.proj.common.security.annotation.Inner;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.Enum.MerchantTypeEnum;
import com.ykht.proj.coupon.Enum.UserTypeEnum;
import com.ykht.proj.coupon.entity.FxMerchantAccount;
import com.ykht.proj.coupon.service.FxMerchantAccountService;
import com.ykht.proj.coupon.vo.FxMerchantAccountVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;


/**
 * b端账户表
 *
 * @author proj code generator
 * @date 2021-08-12 14:10:39
 */
@RestController
@AllArgsConstructor
@RequestMapping("/fxmerchantaccount" )
@Api(value = "fxmerchantaccount", tags = "b端账户表管理")
@Slf4j
public class FxMerchantAccountController {

    private final  FxMerchantAccountService fxMerchantAccountService;

	/**
	 * 用户 服务 Api
	 */
	private final RemoteUserService remoteUserService;

    /**
     * 分页查询 b端账户表
     * @param page 分页对象
     * @param fxMerchantAccountVo b端账户表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    public R<IPage<FxMerchantAccountVo>> getFxMerchantAccountPage(Page page, FxMerchantAccountVo fxMerchantAccountVo) {
		log.info("->分页查询 户表 :{}", page, fxMerchantAccountVo);
		IPage<FxMerchantAccountVo> iPage = fxMerchantAccountService.getFxMerchantAccountPage(page, fxMerchantAccountVo);
        return R.ok(iPage);
    }


    /**
     * 通过id查询b端账户表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('coupon_fxmerchantaccount_view')" )
    public R getById(@PathVariable("id" ) Long id) {
        return R.ok(fxMerchantAccountService.getById(id));
    }

    @ApiOperation(value = "账户信息")
    @GetMapping("/detail" )
    public R detail() {
		FxMerchantAccount account = fxMerchantAccountService.getOne(Wrappers.lambdaQuery(FxMerchantAccount.class).eq(FxMerchantAccount::getTatId, SecurityUtils.getSjId()).eq(FxMerchantAccount::getType,2));
		if (account == null) account = fxMerchantAccountService.cheeckOrCreateAccont(MerchantTypeEnum.brand.getValue(),SecurityUtils.getSjId());
        return R.ok(account);
    }


	/**
	 * 通过id查询b端账户表详情
	 * @param fxMerchantAccountVo b端账户表
	 * @return R
	 */
	@ApiOperation(value = "通过id查询b端账户表详情", notes = "通过id查询b端账户表详情")
	@GetMapping("getByIdAccountDetails" )
	public R<FxMerchantAccountVo> getByIdAccountDetails(FxMerchantAccountVo fxMerchantAccountVo) {
		log.info("->通过id查询b端账户表详情 :{}", fxMerchantAccountVo);
		if (SecurityUtils.getUser().getUserType()== UserTypeEnum.brand.getValue()){
			fxMerchantAccountVo.setTatId(SecurityUtils.getSjId());
			fxMerchantAccountVo.setType(MerchantTypeEnum.brand.getValue());
			fxMerchantAccountVo.setId(null);
			fxMerchantAccountService.cheeckOrCreateAccont(fxMerchantAccountVo.getType(), fxMerchantAccountVo.getTatId());
		}
		FxMerchantAccountVo accountVo = fxMerchantAccountService.getByIdAccountDetails(fxMerchantAccountVo);
		if (accountVo !=null && accountVo.getLoginId()!=null){
			UserVO user = remoteUserService.getByIdUser(accountVo.getLoginId());
			accountVo.setUsername(user.getUsername());
			accountVo.setNickName(user.getNickName());
			accountVo.setUserPhone(user.getPhone());
		}
		return R.ok(accountVo);
	}


	/**
     * 新增b端账户表
     * @param fxMerchantAccount b端账户表
     * @return R
     */
    @ApiOperation(value = "新增b端账户表", notes = "新增b端账户表")
    @SysLog("新增b端账户表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('coupon_fxmerchantaccount_add')" )
    public R save(@RequestBody FxMerchantAccount fxMerchantAccount) {
        return R.ok(fxMerchantAccountService.save(fxMerchantAccount));
    }

    /**
     * 修改b端账户表
     * @param fxMerchantAccount b端账户表
     * @return R
     */
    @ApiOperation(value = "修改b端账户表", notes = "修改b端账户表")
    @SysLog("修改b端账户表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('coupon_fxmerchantaccount_edit')" )
    public R updateById(@RequestBody FxMerchantAccount fxMerchantAccount) {
        return R.ok(fxMerchantAccountService.updateById(fxMerchantAccount));
    }

    /**
     * 通过id删除b端账户表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除b端账户表", notes = "通过id删除b端账户表")
    @SysLog("通过id删除b端账户表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('coupon_fxmerchantaccount_del')" )
    public R removeById(@PathVariable Long id) {
        return R.ok(fxMerchantAccountService.removeById(id));
    }

       
    
    
    @ApiOperation(value = "商户余额列表")
    @PostMapping("ExportExcel")
	@Inner(false)
	public  void ExportExcel(HttpServletResponse response){
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet("商户余额列表");
		HSSFRow row = sheet.createRow((int) 0);
		HSSFCell cell = row.createCell((short) 0);
		cell.setCellValue("序号");
		cell=row.createCell((short)1);
		cell.setCellValue("品牌名称");
		cell=row.createCell((short)2);
		cell.setCellValue("余额");
		cell=row.createCell((short)3);
		cell.setCellValue("累计充值金额");
		cell=row.createCell((short)4);
		cell.setCellValue("可用余额");
		cell=row.createCell((short)5);
		cell.setCellValue("冻结金额");
		cell=row.createCell((short)6);
		cell.setCellValue("提现金额");
		cell=row.createCell((short)7);
		cell.setCellValue("累计消费金额");
		List<FxMerchantAccountVo>list=fxMerchantAccountService.getExport();
		for (int i = 0; i <list.size() ; i++) {
			HSSFRow row1 = sheet.createRow(i + 1);
			FxMerchantAccountVo vo = list.get(i);
			row1.createCell((short)0).setCellValue(vo.getId());
			row1.createCell((short)1).setCellValue(vo.getBrandName());
			row1.createCell((short)2).setCellValue(vo.getBalanceTotal().toString());
			row1.createCell((short)3).setCellValue(vo.getChargeTotal().toString());
			row1.createCell((short)4).setCellValue(vo.getBalance().toString());
			row1.createCell((short)5).setCellValue(vo.getBalanceFrozen().toString());
			row1.createCell((short)6).setCellValue(vo.getWithdrawal().toString());
			row1.createCell((short)7).setCellValue(vo.getConsumeMoney().toString());
		}
		try {
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("2019-09-03.xls", "UTF-8"));
			response.setHeader("Connection", "close");
			response.setHeader("Content-Type", "application/octet-stream");
			wb.write(response.getOutputStream());
			wb.close();
		}catch (Exception e){
			System.out.println("导出失败");
			e.printStackTrace();
		}

	}
}
